("本脚本为子进程，用于写入一个csv文件");

import Fs from "fs-extra";

let titles: null | string[] = null;
let path = "";

/**
 * Csv中的一行，可以是一维数组，也可以是一维Object
 */
export type CsvLine =
  | (number | string | never)[]
  | {
      [key: string]: number | string | never;
    };
export interface CsvAccumArg0 {
  path?: string;
  titles?: string[];
  line?: CsvLine;
  lines?: CsvLine[];
  id?: string;
}

export interface CsvAccumResult {
  complete: boolean;
  id?: string;
}

/**
 * @param {object | string[]}line0 line
 */
function handleLine(line0: CsvLine) {
  if (line0) {
    if (line0 instanceof Array) {
      // 如果是数组，就直接输出就可以了
      let outputData: string[] = line0.map((e) => (e ? `${e}` : ""));
      Fs.appendFileSync(path, "\n" + outputData.join(","));
    } else {
      // 如果是对象
      if (titles === null) {
        titles = Object.keys(line0); // 如果还没有分配titles
        Fs.writeFileSync(path, titles.join(","));
      }
      const line = titles.map((key) => (line0[key] ? line0[key] : "")); // 根据titles顺序变为字符串数组
      Fs.appendFileSync(path, "\n" + line.join(",")); // 把一行数据加上
    }
  }
}

/**
 * @param {object}root0 传入的msg
 * @param {string}root0.path 目标路径
 * @param {string[]}root0.titles titles
 * @param {object | string[]}root0.line line
 * @param {string}root0.id id
 */
function handleData({
  path: path0,
  titles: titles0,
  line: line0, // 单行传入
  lines: lines0, // 多行传入
  id = "",
}: CsvAccumArg0): void {
  if (path0) {
    path = path0;
    // 给定了path之后，搞一个空文件
    Fs.ensureFileSync(path0);
    Fs.writeFileSync(path, "");
  }
  if (titles0) {
    // 如果传入了titles
    titles = titles0;
    Fs.writeFileSync(path, titles.join(","));
  }
  if (line0) {
    // 如果单行传入()
    handleLine(line0);
    // @ts-expect-error
    line0 = null; // 释放内存
  }
  if (lines0) {
    // 如果多行传入
    for (let line1 of lines0) {
      handleLine(line1);
      // @ts-expect-error
      line1 = null; // 释放内存
    }
    // @ts-expect-error
    lines0 = null; // 释放内存
  }
  let result: CsvAccumResult = { complete: true, id };
  // @ts-ignore
  process.send(result);
}

/**
 * 用于接收主进程发来的数据
 */
process.on("message", handleData);
